<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/6/11 15:36
 */

namespace App\Project\Traits;

use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Database\Eloquent\Builder;

trait SearchAbleForModel
{
//    protected $searchAbleField = [
//        数据库字段             请求字段
//        'name'           => 'name',
//        'phone'          => 'phone',
//        'medical_number' => 'medical_number',
//    ];
//


    /**
     * @param \Illuminate\Database\Eloquent\Builder $builder
     * @param \Illuminate\Http\Request           $request
     * @return \Illuminate\Database\Query\Builder
     */
    public function scopeSearch(Builder $builder, Request $request)
    {
        $field = $this->getSearchAbleField();

        if (!empty($field)) {

            $where = collect(Arr::only($request->all(), $field));
            $flipFields = array_flip($field);

            $where->map(function ($value, $key) use (&$builder, $flipFields) {

                $method = 'where' . ucfirst($flipFields[$key]);

                $builder = $builder->$method($value);
            });
        }

        return $builder;
    }

    /**
     * 获取请求字段与数据库字段的对照map
     * @return array
     */
    protected function getSearchAbleField()
    {
        if (property_exists($this, 'searchAbleField')) {
            return $this->searchAbleField ?: [];
        }

        return [];
    }
}